import { FC, useRef } from 'react'
import { ModalForm, ProFormInstance, ProFormSelect } from '@ant-design/pro-form'
import { Button, message } from 'antd'
import { EnvironmentSetServerDTO } from '@/model/efficient/EnvironmentSetServerDTO'
import { getAllServer } from '@/api/efficient/server'
import { getEnvironmentServer, setEnvironmentServer } from '@/api/efficient/environment'

interface SetServerParam {
  environmentId: number
}

const EnvironmentSetServerForm: FC<SetServerParam> = (props) => {
  const { environmentId } = props
  const formRef = useRef<ProFormInstance>()
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  }
  /**
   * 根据环境id获取服务器
   */
  const getServerByEnvironment = async (visible: boolean) => {
    if (visible) {
      const environmentServers = await getEnvironmentServer(environmentId)
      formRef.current?.setFieldsValue({
        serverIds: environmentServers.map((item) => item.serverId),
      })
    }
  }
  return (
    <div className="environment-set-server-form">
      <ModalForm<EnvironmentSetServerDTO>
        formRef={formRef}
        title="设置服务器"
        layout="horizontal"
        trigger={
          <Button type="link">
            设置服务器
          </Button>
        }
        onVisibleChange={getServerByEnvironment}
        {...formItemLayout}
        onFinish={async (values) => {
          const reqData: EnvironmentSetServerDTO = new EnvironmentSetServerDTO()
          reqData.environmentId = environmentId
          reqData.serverIds = values.serverIds
          await setEnvironmentServer(reqData)
          message.success('设置成功')
          return true
        }}
      >
        <ProFormSelect
          mode="multiple"
          name="serverIds"
          label="服务器"
          placeholder="服务器"
          request={async () => {
            const serverLists = await getAllServer()
            return serverLists.map((item) => {
              return {
                label: `${item?.name}  ${(item?.publicIp || item?.privateIp)}`,
                value: item.id,
              }
            })
          }}
        />
      </ModalForm>
    </div>
  )
}

export default EnvironmentSetServerForm
